package com.sto.stoapp.activity.scanner;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.dataprocess.ProcessScanCode;
import com.sto.stoapp.dataprocess.parcelable.GetTableParcel;
import com.sto.stoapp.dataprocess.parcelable.SelectTableParcel;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.SqlSelectTableManager;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.SoundManager;
import com.sto.stoapp.scan.ScanRuleManager;
import com.sto.stoapp.status.EnumScanCode;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.util.BillFilterUtil;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.UnifiedStaticType;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoListenerActivity;

import java.util.ArrayList;
import java.util.List;

@SuppressLint("HandlerLeak")
public class StoScanBagAndSendPieceActivity extends StoListenerActivity {

    private DataBusinessEntity dataBusiness;
    private List<EditText> edit = new ArrayList<EditText>();
    private StoHhmEditText nextStation, carID, bagNumber;

    private String nextStationCode = "", nextStationName = "";

    private final int COURIER_RESULT = 0xfe;
    private boolean FALG = false;// 修改包号 标志位（是否修改）

    // 24小时上传到服务器需要做一个区分，用1表示
    private boolean IS_24HOURS = false;

    private String busiType = HomeBroadAction.SCANNER_MAN_BROAD;

    // 扫描结果
    protected static final int HAND_RESULT = 0x4f;

    public static final String A = "A";// 1 0
    public static final String B = "B";// 0
    // public static final String D = "D";
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == HAND_RESULT) {
                handlerScanData(msg.obj.toString());
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sto_scanning_bagging_send_piece);
        Bundle extras = getIntent().getExtras();
        busiType = extras.getString("busiType");
        this.setTitleBottom(R.string.package_send_piece, busiType);

        IS_24HOURS = this.getIntent().getBooleanExtra(
                UnifiedStaticType.IS_24HOURS, false);
        // System.out.println(IS_24HOURS + "");
        dataBusiness = new DataBusinessEntity();
        dataBusiness.initInsertData();
        initWidget();
        initListen();
        initScanListener();
        if (busiType.equals(HomeBroadAction.SCANNER_MAN_BROAD)) {
            initScanRecordAdapter(EnumTableNames.STATUS_TABLE_BAGGINGADNSENDPIECE);
        } else if (busiType.equals(HomeBroadAction.CENTER_BROAD)) {
            initScanRecordAdapter(EnumTableNames.STATUS_TABLE_CENTER_BAGGINGADNSENDPIECE);
        }
    }

    // 初始化控件
    private void initWidget() {
        nextStation = (StoHhmEditText) this
                .findViewById(R.id.sanning_next_station);
        carID = (StoHhmEditText) this.findViewById(R.id.sanning_carID);
        bagNumber = (StoHhmEditText) this
                .findViewById(R.id.scanning_bag_number);
        code = (StoHhmEditText) this.findViewById(R.id.sanning_code);
        initPointLayout(true);

        edit.add(nextStation);
        edit.add(carID);
        edit.add(bagNumber);
        edit.add(code);
        if (busiType.equals(HomeBroadAction.SCANNER_MAN_BROAD)) {
            addUploadTable(EnumTableNames.STATUS_TABLE_BAGGINGADNSENDPIECE);
            addUploadTable(EnumTableNames.STATUS_TABLE_SCANNING_BAGGING_OPERATE);
        } else if (busiType.equals(HomeBroadAction.CENTER_BROAD)) {
            addUploadTable(EnumTableNames.STATUS_CENTER_TABLE_BAGGING_OPERATE);
            addUploadTable(EnumTableNames.STATUS_TABLE_CENTER_BAGGINGADNSENDPIECE);
        }
    }

    @SuppressLint("NewApi")
    private boolean CheckItemData(String barcode) {
        boolean ret = false;
        if (nextStationCode.isEmpty()) {
            Helper.showSoundToast(this, "请选择正确的站点!", false);
            nextStation.setText("");
            nextStation.requestFocus();
            return ret;
        }
        if (!nextStationName.equals(nextStation.getText().toString())) {
            Helper.showSoundToast(this, "请选择正确的站点!", false);
            nextStation.setText("");
            nextStation.requestFocus();
            return ret;
        }
        if (carID.getText().toString().length() > 0
                && carID.length() != CARID_LENGTH) {
            Helper.showSoundToast(this,
                    getString(R.string.car_id_median_error), false);
            carID.setText("");
            carID.requestFocus();
            return ret;
        }
        if (carID.getText().toString().length() > 0
                && !carID.getText().toString().matches("[0-9]+")) {
            Helper.showSoundToast(this, "车辆id非法", false);
            carID.setText("");
            carID.requestFocus();
            return ret;
        }

        return CheckScanCode(barcode);
    }

    private boolean CheckScanCode(String code) {
        EnumScanCode status = ProcessScanCode.getInstance(this)
                .ScanCodeResolve(code,
                        EnumTableNames.STATUS_TABLE_BAGGINGADNSENDPIECE);
        if (status != EnumScanCode.CODE_WAY_BILL) {
            Helper.showSoundToast(this, status.message, false);
            return false;
        }
        return true;
    }

    // 处理扫描数据
    @SuppressLint("NewApi")
    private void processScanData() {
        try {
            String bag = bagNumber.getText().toString();
            if (bag.isEmpty()) {
                Helper.showSoundToast(this, "袋号不能为空!", false);
                ScanOpen();
                return;
            }
            if (ScanRuleManager.getInstance(this).isBagCode(bag)) {

                //Add by wj过滤单号
                boolean isFilter= BillFilterUtil.isFilter(code.getText().toString().trim(),this);
                if(isFilter){
                    showFilterDialog(code.getText().toString().trim());
                    return;
                }
                //End by wj

                if (addPieceRecord(bag)) {
                    // this.addCodeNumber();
                    setSaveData(true);
                    // SoundManager.getInstance(this).playSuccessSound();
                    Helper.showSoundAndVibrator(this, true);
                    addScanRecordInfo(code.getText().toString());
                    code.setText("");
                    FALG = true;
                }
                // 提示插入数据失败
                else {
                    Helper.showSoundToast(this,
                            getString(R.string.code_repeat), false);
                }
            } else {
                Helper.showSoundToast(StoScanBagAndSendPieceActivity.this,
                        "错误袋号!", false);
                bagNumber.setText("");
                bagNumber.requestFocus();
            }

        } catch (Exception e) {
            e.printStackTrace();
            ExceptionLog.writeLog("processScanData", e.getMessage());
        } finally {
            ScanOpen();
        }
    }

    // 增加一条记录
    private boolean addPieceRecord(String bag) {

        dataBusiness.initInsertData();
        boolean ret = false;
        if (code.getText().toString().length() > 3) {

        } else {
            Helper.showSoundToast(this, "单号位数错误", false);
            code.setText("");
            code.requestFocus();
            return false;
        }

        if (IS_24HOURS) {
            ret = doInsertPacketOprTab(bag, "1", "");
        } else {
            ret = doInsertPacketOprTab(bag, "", "");
        }

        if (IS_24HOURS) {
            ret = doInsertBAGSendPieceTab("1");

            // ret = doInsertSendPieceTab(code.getText().toString(), "1",
            // ScanTypeEntity.TYPE_SCAN_BAGANDSEND);
        } else {
            ret = doInsertBAGSendPieceTab("");

            // ret = doInsertSendPieceTab(code.getText().toString(), "",
            // ScanTypeEntity.TYPE_SCAN_BAGANDSEND);
        }

        return ret;
    }

    /**
     * 插入袋操作
     *
     * @param express_type
     * @param different_flag 区别装袋发件
     */
    private boolean doInsertPacketOprTab(String Bar_code_number,
                                         String express_type, String different_flag) {
        boolean ret;
        dataBusiness.initInsertData();
        // 网点编号
        dataBusiness.setNet_code(StoFilePreference.getInstance(this)
                .getSiteCode());
        // 工号
        dataBusiness.setJob_number(StoFilePreference.getInstance(this)
                .getUserCode());
        // 下一站名称
        dataBusiness.setUser_defined3(nextStation.getText().toString());

        dataBusiness.setBar_code_number(Bar_code_number);

        dataBusiness.setCodeType(getExpType(Bar_code_number));
        // 下一站
        dataBusiness.setNext_station(nextStationCode);
        // 车辆ID
        dataBusiness.setCarID_number(carID.getText().toString());
        // 袋号
        dataBusiness.setBag_number(bagNumber.getText().toString());
        dataBusiness.setExpress_type(express_type);
        dataBusiness.setDifferent_flag(different_flag);
        ret = insertSendPieceTab();
        if (ret) {
            this.addCodeNumber();
        }
        return ret;
    }

    /**
     * 插入装袋发件表
     */
    private boolean doInsertBAGSendPieceTab(String express_type) {
        boolean ret;
        dataBusiness.initInsertData();
        // 网点编号
        dataBusiness.setNet_code(StoFilePreference.getInstance(this)
                .getSiteCode());
        // 工号
        dataBusiness.setJob_number(StoFilePreference.getInstance(this)
                .getUserCode());
        // 下一站名称
        dataBusiness.setUser_defined3(nextStation.getText().toString());

        // 下一站
        dataBusiness.setNext_station(nextStationCode);
        // 车辆ID
        dataBusiness.setCarID_number(carID.getText().toString());
        dataBusiness.setBar_code_number(code.getText().toString());
        dataBusiness.setCodeType(getExpType(code.getText().toString()));
        // 袋号
        dataBusiness.setBag_number(bagNumber.getText().toString());
        dataBusiness.setExpress_type(express_type);
        dataBusiness.setDifferent_flag("");
        ret = insertBAGSendPieceTab();
        if (ret) {
            this.addCodeNumber();
        }
        return ret;
    }

    private boolean insertSendPieceTab() {
        boolean ret = false;
        if (busiType.equals(HomeBroadAction.SCANNER_MAN_BROAD)) {
            dataBusiness
                    .setCommand_type(EnumTableNames.STATUS_TABLE_SCANNING_BAGGING_OPERATE
                            .getOpCode());
            ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
                    EnumTableNames.STATUS_TABLE_SCANNING_BAGGING_OPERATE);

        } else if (busiType.equals(HomeBroadAction.CENTER_BROAD)) {
            dataBusiness
                    .setCommand_type(EnumTableNames.STATUS_CENTER_TABLE_BAGGING_OPERATE
                            .getOpCode());
            ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
                    EnumTableNames.STATUS_CENTER_TABLE_BAGGING_OPERATE);
        }
        return ret;
    }

    private boolean insertBAGSendPieceTab() {
        boolean ret = false;

        if (busiType.equals(HomeBroadAction.SCANNER_MAN_BROAD)) {
            dataBusiness
                    .setCommand_type(EnumTableNames.STATUS_TABLE_BAGGINGADNSENDPIECE
                            .getOpCode());
            ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
                    EnumTableNames.STATUS_TABLE_BAGGINGADNSENDPIECE);
        } else if (busiType.equals(HomeBroadAction.CENTER_BROAD)) {
            dataBusiness
                    .setCommand_type(EnumTableNames.STATUS_TABLE_CENTER_BAGGINGADNSENDPIECE
                            .getOpCode());
            ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
                    EnumTableNames.STATUS_TABLE_CENTER_BAGGINGADNSENDPIECE);
        }
        return ret;
    }

    // 初始化监听
    private void initListen() {

        nextStation.setEditDelete(new EditClickListener() {

            @Override
            public void onEditDelete() {
                onBackPressed();
            }

            @Override
            public void onEditClickListener(View v) {
//                selectNextStation();
            }
        });
        findViewById(R.id.btn_select).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectNextStation();
            }
        });
        carID.setEditDelete(new EditClickListener() {

            @Override
            public void onEditDelete() {
                nextStation.requestFocus();
                // nextStation.setSelection(nextStation.getText().toString()
                // .length());
            }

            @Override
            public void onEditClickListener(View v) {
                if (carID.getText().toString().length() > 0
                        && carID.length() != CARID_LENGTH) {
                    Helper.showSoundToast(StoScanBagAndSendPieceActivity.this,
                            getString(R.string.car_id_median_error), false);
                    carID.setText("");
                    carID.requestFocus();
                    return;
                }
                if (carID.getText().toString().length() > 0
                        && !carID.getText().toString().matches("[0-9]+")) {
                    Helper.showSoundToast(StoScanBagAndSendPieceActivity.this,
                            "车辆id非法", false);
                    carID.setText("");
                    carID.requestFocus();

                    return;
                }

                bagNumber.requestFocus();
            }
        });
        /*
		 * carID.setOnKeyListener(new StoOnKeyListener(this) {
		 * 
		 * @Override public boolean OnKeyListener(View view, int position,
		 * KeyEvent event) { if (position == KeyEvent.KEYCODE_DPAD_CENTER) {
		 * 
		 * bagNumber.requestFocus();
		 * 
		 * return true; } return false; } });
		 */

        bagNumber.setEditDelete(new EditClickListener() {

            @Override
            public void onEditDelete() {
                carID.requestFocus();
                // carID.setSelection(carID.getText().toString().length());
            }

            @Override
            public void onEditClickListener(View v) {
                String bag = bagNumber.getText().toString();
                if (bag.length() <= 0) {
                    Helper.showSoundToast(StoScanBagAndSendPieceActivity.this,
                            getString(R.string.code_empty), false);
                    return;
                }
                if (ScanRuleManager.getInstance(
                        StoScanBagAndSendPieceActivity.this).isBagCode(bag)) {
                    code.requestFocus();
                } else {
                    Helper.showSoundToast(StoScanBagAndSendPieceActivity.this,
                            getString(R.string.bag_code_error), false);
                }

            }
        });

        code.setEditDelete(new EditClickListener() {

            @Override
            public void onEditDelete() {
                bagNumber.requestFocus();
            }

            @Override
            public void onEditClickListener(View v) {
                codeProcess();

            }
        });

        for (EditText editListener : edit) {
			/*
			 * 监听EditText内容个数
			 */
            editListener.addTextChangedListener(new TextWatcher() {

                @SuppressLint("NewApi")
                @Override
                public void onTextChanged(CharSequence s, int start,
                                          int before, int count) {
                    // 控件没有内容就清空编号
                    if (nextStation.getText().toString().isEmpty()) {
                        nextStationCode = "";
                        nextStationName = "";
                    }
                    if (bagNumber.getText().toString().isEmpty()) {
                        FALG = false;
                    }
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start,
                                              int count, int after) {
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
        }
    }

    private void codeProcess() {
        String codeName = code.getText().toString();

        GetTableParcel data;
        if (codeName.length() == 0) {
            Helper.showSoundToast(this, getString(R.string.code_empty), false);
        } else {
            if (codeName.length() == NEXT_STATION_LENGTH) {
                data = queryNextStation(codeName);
                if (data != null) {
                    nextStation.setText(data.getSelectName());
                    nextStationCode = data.getSelectCode();
                    nextStationName = data.getSelectName();
                } else {
                    nextStationName = "";
                    Helper.showSoundToast(this, getString(R.string.undefined),
                            false);
                }
                code.setText("");

            } else {
                if (CheckScanCode(code.getText().toString())) {
                    Message msg = handler.obtainMessage();
                    msg.what = HAND_RESULT;
                    msg.obj = code.getText().toString();
                    handler.sendMessage(msg);
                } else {
                    code.setText("");
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == COURIER_RESULT && resultCode == RESULT_OK) {
            GetTableParcel courierEntity = data.getParcelableExtra("Name");
            if (courierEntity != null) {
                nextStation.setText(courierEntity.getSelectName());
                nextStation.setSelection(nextStation.length());
                nextStationCode = courierEntity.getSelectCode();

                if (nextStationCode.length() > 0)
                    nextStationName = courierEntity.getSelectName();
                bagNumber.requestFocus();
            }
        } else if (requestCode == COURIER_RESULT
                && resultCode == RESULT_FIRST_USER) {
            nextStation.setText("");
            nextStationName = "";
            Helper.showSoundToast(StoScanBagAndSendPieceActivity.this,
                    getString(R.string.undefined), false);
        }
    }

    private void selectNextStation() {
        try {
            SelectTableParcel tableParcel = new SelectTableParcel();
            if (nextStation.getText().toString().length() == 0) {
                tableParcel
                        .setSelectSql(SqlSelectTableManager.SQL_NEXT_NETSITE_ALL);
                tableParcel.setSelectField(new String[]{});
            } else {
                tableParcel
                        .setSelectSql(SqlSelectTableManager.SQL_NEXT_NETSITE_ONLY_LIKE);
                tableParcel.setSelectField(new String[]{"%"
                        + nextStation.getText().toString() + "%"});
            }
            tableParcel.setSelectCode(SITE_CODE_NUMBER);
            tableParcel.setSelectName(SITE_CODE_NAME);
            tableParcel.setProperty(null);
            Intent intent = new Intent(StoScanBagAndSendPieceActivity.this,
                    StoSelectTableActivity.class);
            intent.putExtra("tableData", tableParcel);

            startActivityForResult(intent, COURIER_RESULT);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionLog.writeLog("selectNextStation", e.getMessage());
        }
    }

    @Override
    public void onBackPressed() {
        // 确定退出吗?
        showNotice();
        // super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        edit.clear();
        edit = null;
        handler.removeMessages(HAND_RESULT);
        super.onDestroy();
    }

    @Override
    protected void handlerScanData(String scanData) {

        if (scanData != null && !scanData.equals("")) {
            String result = scanData;
            // 下一站
            if (nextStation.hasFocus() || result.length() == CARID_LENGTH) {
                nextStation.setText(result);
                selectNextStation();
                SoundManager.getInstance(StoScanBagAndSendPieceActivity.this)
                        .playSuccessSound();
            }
            // 车辆ID
            else if (carID.hasFocus() && result.length() == CARID_LENGTH) {
                carID.setText(result);
            }
            // 袋号
            else if (bagNumber.hasFocus() && ScanRuleManager.getInstance(this).isBagCode(result)) {
                bagNumber.setText(result);
                code.requestFocus();
                SoundManager.getInstance(StoScanBagAndSendPieceActivity.this)
                        .playSuccessSound();
            } else if (code.hasFocus()) {
                code.setText("");
                code.setText(result);
                code.setSelection(code.length());
                if (CheckItemData(result)) {
                    processScanData();
                }
                code.setText("");
            } else {
                Helper.showSoundToast(StoScanBagAndSendPieceActivity.this,
                        "错误条码!", false);
            }

        }

    }
}
